<template>
    <div class="order-address" :class="{active: !!type}">

        <!-- 正常状态 -->
        <div class="address-detail" v-if="type != 'address'">
            <h2>
                <strong>Shipping address</strong>
                <span @click="doEdit('address')">Edit</span>
            </h2>

            <div class="address-detail-info" :class="{ warning: info.order_state == 14 }">
                <h3 v-if="address.first_name" v-text="address.first_name"></h3>
                <p v-if="address.phone" v-text="address.phone"></p>
                <p v-if="address.email" v-text="address.email"></p>
                <p v-if="address.street" v-text="address.street"></p>
                <p v-if="address.district" v-text="address.district"></p>
                <p v-text="[address.city,address.state,address.post_code].filter(i=>i).join(',')"></p>
                <p v-text="address.country"></p>
            </div>

            <div class="address-detail-notify" v-if="info.order_state == 14">
                <svg-icon name="notify2" />
                <span>The address in this order cannot be delivered. Please change the shipping address.</span>
            </div>

            <div class="address-detail-remote" v-if="remoteSign">
                <OrderRemoteSign :post_code="address.post_code" />
            </div>

        </div>

        <div class="address-logistics" v-if="type != 'address'">
            <h2>
                <strong>Shipping method </strong>
                <span @click="doEdit('shipping')" v-if="type != 'shipping' && info.order_state != 14">Edit</span>
            </h2>

            <!-- 选择物流 -->
            <div class="address-logistics-select" v-if="type == 'shipping'">
                <ul>
                    <li v-for="item in logistics" :key="item.no" :class="{ active: item.no == cache }" @click="cache = item.no">
                        <i></i>
                        <strong v-text="item.name + ' shipping'"></strong>
                        <span>
                            <em>{{ item.need_time_min }} - {{ item.need_time_max }}</em>
                            <b>business days</b>
                        </span>
                        <CommonCurrencyRate :price="item.price" :cover="currencyCover" />
                    </li>
                </ul>

                <p>Shipping timeframe excludes production lead time.</p>

                <fieldset>
                    <button @click="doCancel()">Cancel</button>
                    <button type="primary" @click="saveShipping('shipping',logisticsActive)">Save</button>
                </fieldset>
            </div>

            <template v-else-if="logisticsActive">

                <div class="address-logistics-info">
                    <strong v-text="(logisticsActive.name + ' shipping') || 'Logistics is loading'"></strong>
                    <span>
                        <em>{{ logisticsActive.need_time_min }} - {{ logisticsActive.need_time_max }}</em>
                        <b>business days</b>
                    </span>
                    <CommonCurrencyRate :price="logisticsActive.price" :cover="currencyCover" />

                </div>
                <div class="address-logistics-timeframe">
                    <p>Shipping timeframe excludes production lead time.</p>
                </div>
            </template>

            <div class="address-logistics-error" v-else>
                <img src="@/assets/images/order/dialog-shipping-empty.png" alt="">
                <span>No logistics information</span>
            </div>

            <UxLoading2 :loading="loading" />

        </div>

        <!-- 修改地址 -->
        <div class="address-input" v-if="type == 'address'">
            <h2><strong>Shipping address</strong></h2>
            <CommonAddressForm v-model="form" @submit="saveAddress($event)" @validate="forbid = !!$event" />
            <div class="form-button">
                <button @click="doCancel()">Cancel</button>
                <button type="primary" :disabled="forbid" @click="saveAddress($event)">Save</button>
            </div>

            <UxLoading2 :loading="loading" />
        </div>

    </div>
</template>
<script>
export default {
    props: {
        info: { type: Object, default: () => ({}) },
        logistics: { type: Array, default: () => [] },
        getLogistics: { type: Function, default: () => undefined },
    },
    data () {
        return {
            type: "",
            loading: false,
            form: null,
            forbid: false,
            cache: '',
            error: null,
        };
    },
    computed: {
        currencyCover () { return this.info || {} },

        // 地址
        address () {
            return (this.info || {}).address || {};
        },
        remoteSign () {
            const info = this.info || {}
            const logistics = info.logistics || {}
            return !!logistics.remote_sign
        },

        // 物流地址
        logisticsActive () {
            const logistics = (this.info || {}).logistics || {}
            const channel = (this.cache || logistics.my_logistics_channel || '').toUpperCase();
            const active = this.logistics.find(i => i.no == channel);
            return active || this.logistics[0]
        },
    },
    methods: {

        doCancel () {
            if (this.type == 'shipping' && this.form) {
                // this.type = 'address'
                this.type = '';
                this.form = null;
                this.cache = '';
            } else {
                this.type = '';
                this.form = null;
                this.cache = '';
            }
        },
        // 重新修改地址
        doEdit (type) {
            if (type == 'address') {
                this.form = JSON.parse(JSON.stringify(this.info.address));
                this.type = 'address';
            } else if (type == 'shipping') {
                const logistics = (this.info || {}).logistics || {}
                this.cache = logistics.my_logistics_channel || '';
                this.type = 'shipping';
            }
        },

        // 保存地址
        async saveAddress (event) {

            if (this.address.country_code != this.form.country_code || this.address.post_code != this.form.post_code) {
                // 获取地址
                this.loading = true;
                this.getLogistics(this.info, this.form.country_code, this.form.post_code).then(result => {

                    const logistics = (this.info || {}).logistics || {}
                    const active = result.find(i => i.no == logistics.my_logistics_channel) || result[0];
                    const channel = active ? active.no || '' : '';

                    this.cache = channel;
                    this.$emit('update:logistics', result)
                    this.saveShipping('address', active, response => {
                        this.loading = false;
                        this.type = 'shipping';
                        this.$uxMessage.warning('Delivery address was updated. Shipping rates & transit time may change accordingly.')
                    });
                }).catch(error => {
                    // 保存失败
                    this.$uxMessage.error(error)
                    this.loading = false;
                })
            } else {
                this.saveShipping('address', this.logisticsActive);
            }
        },

        // 设置物流
        async saveShipping (type, shipping, callback) {

            const pricing = (this.info || {}).pricing || {}
            const logisticsActive = shipping || {};
            const address = this.form || this.address;

            // 订单地址再次保存
            const request = {
                first_name: address.first_name || '', // string 名称
                city: address.city || '', // string 城市
                state: address.state || '', // string 省、州
                district: address.district || '', // string
                street: address.street || '', // string
                house_number: address.house_number || '', // string
                company: address.company || '', // string
                email: address.email || '', // string
                phone: address.phone || '', // string
                phone2: address.phone2 || '', // string
                post_code: address.post_code || '', // string
                country_code: address.country_code || '', // string 国家二字码
                country: address.country || '', // string 国家名称
                logistics_channel_no: logisticsActive.no || '', // string 物流渠道号
                tax_price: logisticsActive.tax_price || 0, // int32 税费
                logistics_price: logisticsActive.price || 0, // int32 物流价格
                remote_sign: logisticsActive.remote_sign,
                total_money: 0, // int32 订单总金额
            };

            const total_money = pricing.commodity_prices + logisticsActive.tax_price + logisticsActive.price + pricing.tag_price + pricing.pack_price;


            request.total_money = parseInt(total_money) || 0;

            this.loading = true;
            const result = await this.$http(
                "Order.setOrderAddress/" + this.info.order_code,
                request
            );

            if (this.form) {
                Object.keys(this.form).map(key => {
                    this.$set(this.address, key, this.form[key])
                })
            }

            if (this.cache) {
                this.$set(this.info.pricing, 'tax_price', request.tax_price)
                this.$set(this.info.pricing, 'logistics_price', request.logistics_price)
                this.$set(this.info.pricing, 'total_money', request.total_money)
                this.$set(this.info.logistics, 'my_logistics_channel', request.logistics_channel_no)
                this.$set(this.info.logistics, 'remote_sign', request.remote_sign)
            }


            // 问题订单要刷新状态
            if (this.info.order_state == 14 && this.$parent.$parent.getOrderStatus) {
                await this.$parent.$parent.getOrderStatus()
            }


            if (callback) {
                this.$emit('global:ORDER_UPDATA_PRICE', this.info);
                callback(result);
            } else if (result.code === 0) {
                // this.$uxMessage.success("Address changed successfully");

                if (type == 'address') {
                    this.$uxMessage.success("Address changed successfully");
                } else if (type == 'shipping') {
                    this.$uxMessage.success("Shipping changed successfully");
                }

                this.type = '';
                this.cache = '';
                this.form = null;
                this.loading = false;
                this.$emit('global:ORDER_UPDATA_PRICE', this.info);
            } else {
                this.loading = false;
                this.$uxMessage.error("Failed to save address");
            }

        },
    },
    created () {
    }
};
</script>
<style lang="scss" scoped>
.order-address {
    position: relative;
    display: flex;

    &::v-deep {
        &.active ~ .order-sidebar .order-sidebar-billing {
            button {
                color: #9e9e9e;
                pointer-events: none;
                background: #ebebeb;
                border: 1px solid #e0e0e0;
            }
        }
    }
}

.address-detail,
.address-logistics,
.address-input {
    position: relative;
    padding: 40px 14px 14px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    background: #ffffff;
    border-radius: 8px;
    border: 1px solid #e6e6e6;
    display: flex;
    flex-direction: column;

    & > h2 {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        display: flex;
        align-items: center;
        height: 40px;
        border-bottom: 1px solid #e6e6e6;
        line-height: 40px;
        padding: 0 12px;
        box-sizing: border-box;

        strong {
            font-size: 16px;
            font-family: Roboto-Medium, Roboto;
            font-weight: 500;
            color: #000000;
            line-height: 20px;
            white-space: nowrap;
        }
        span {
            margin-left: 4px;
            font-size: 14px;
            font-family: Roboto, Roboto;
            font-weight: 400;
            color: #087196;
            line-height: 18px;
            cursor: pointer;
            text-decoration: underline;
            &:hover {
                color: #287e9c;
                text-decoration: none;
            }
        }
    }
}

.address-detail {
    flex: 432;
    position: relative;

    .address-detail-info {
        display: flex;
        flex-direction: column;
        justify-content: center;
        padding: 6px;
        margin-top: 14px;
        h3 {
            text-overflow: -o-ellipsis-lastline;
            overflow: hidden; //溢出内容隐藏
            text-overflow: ellipsis; //文本溢出部分用省略号表示
            display: -webkit-box; //特别显示模式
            -webkit-line-clamp: 2; //行数
            line-clamp: 2;
            -webkit-box-orient: vertical; //盒子中内容竖直排列
            font-size: 24px;
            font-family: Roboto-Medium, Roboto;
            font-weight: 500;
            color: #000000;
            line-height: 28px;
            margin-bottom: 4px;
        }

        p {
            margin-top: 14px;
            font-size: 16px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #000000;
            line-height: 16px;
        }

        &.warning {
            box-sizing: border-box;
            min-height: 142px;
            padding: 14px;
            background: rgba(200, 13, 17, 0.04);
            border-top: 1px dashed #c62828;
            border-bottom: 1px dashed #c62828;
        }
    }

    .address-detail-notify {
        display: flex;
        margin-top: 14px;
        color: #c62828;
        svg {
            width: 14px;
            height: 14px;
            min-width: 14px;
            margin-top: 4px;
        }

        span {
            margin-left: 4px;
            font-size: 14px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            line-height: 22px;
        }
    }

    & > .address-detail-remote {
        height: 40px;
        & > .remote-sign {
            position: absolute;
            bottom: 0;
            left: 12px;
            right: 12px;
            padding: 10px 0;
        }
    }
}

.address-logistics {
    flex: 348;
    margin-left: 12px;
    overflow: hidden;

    .address-logistics-error {
        display: flex;
        height: 100%;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        svg,
        img {
            width: 60px;
            height: 46px;
        }
        span {
            margin-top: 12px;
            font-size: 14px;
            font-family: Roboto, Roboto;
            font-weight: 400;
            color: #757575;
            line-height: 16px;
            display: block;
            white-space: normal;
            word-break: break-word;
        }
    }

    .address-logistics-info {
        display: flex;
        flex-direction: column;
        strong {
            display: block;
            font-size: 16px;
            font-family: Roboto-Medium, Roboto;
            font-weight: 500;
            color: #000000;
            line-height: 20px;
        }
        span {
            margin-top: 10px;
            font-size: 16px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #000000;
            line-height: 18px;
            b {
                font-weight: inherit;
            }
        }

        p {
            margin-top: 4px;
            font-size: 12px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #555555;
            line-height: 18px;
            &::before {
                content: '*';
                color: #c62828;
                margin-right: 2px;
            }
        }

        .currency-rate {
            margin-top: 10px;
            font-size: 16px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #000000;
            line-height: 16px;
            justify-content: flex-start;
        }
    }

    .address-logistics-timeframe {
        p {
            position: absolute;
            border-top: 1px dashed #e6e6e6;
            left: 10px;
            bottom: 0;
            right: 10px;
            padding: 10px 0;
            font-size: 12px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #000;
            line-height: 18px;
            &::before {
                content: '*';
                color: #c62828;
                margin-right: 2px;
            }
        }
    }

    .address-logistics-select {
        display: flex;
        flex-direction: column;
        flex: 1;
        ul {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            padding: 10px 0;
        }
        li {
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            position: relative;
            padding: 10px 10px 10px 36px;
            border-radius: 8px;
            transition: background 0.2s;
            cursor: pointer;

            & + li {
                margin-top: 10px;
            }

            & > i {
                position: absolute;
                left: 10px;
                width: 14px;
                height: 14px;
                border-radius: 9px;
                border: 2px solid #737373;
                transition: border 0.2s;
                &::after {
                    content: '';
                    position: absolute;
                    left: 50%;
                    top: 50%;
                    width: 6px;
                    height: 6px;
                    background: #ea4c89;
                    border-radius: 9px;
                    opacity: 0;
                    transform: translate(-50%, -50%);
                    transition: opacity 0.2s;
                }
            }

            strong {
                font-size: 16px;
                font-family: Roboto-Regular, Roboto;
                font-weight: 400;
                color: #000000;
                line-height: 18px;
            }

            span {
                margin-top: 8px;
                font-size: 14px;
                font-family: Roboto-Regular, Roboto;
                font-weight: 400;
                color: #555555;
                line-height: 16px;
                em {
                    font-style: normal;
                }
                b {
                    font-weight: inherit;
                }
            }
            .currency-rate {
                margin-top: 10px;
                font-size: 14px;
                font-family: Roboto-Regular, Roboto;
                font-weight: 400;
                color: #555555;
                line-height: 16px;
            }

            &:hover {
                background-color: #f6f6f6;
            }

            &.active {
                & > i {
                    border-color: #ea4c89;
                    &::after {
                        opacity: 1;
                    }
                }
            }
        }

        & > p {
            padding: 20px 0;
            font-size: 12px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #555555;
            line-height: 18px;
            border-top: 1px dashed #e6e6e6;
            border-bottom: 1px solid #ededed;
            &::before {
                content: '*';
                color: #c62828;
                margin-right: 2px;
            }
        }

        fieldset {
            margin-top: 12px;
            width: 100%;
            display: flex;
            justify-content: center;

            button {
                width: 88px;
                height: 36px;
                margin: 0 4px;
            }
        }
    }
}

.address-input {
    position: relative;
    display: flex;
    flex-wrap: wrap;
    padding-bottom: 0;
    overflow: hidden;

    .address-form {
        padding-top: 18px;
        margin: 0 -16px;
        width: calc(100% + 32px);
        &::v-deep .el-form-item {
            padding-left: 16px;
            padding-right: 16px;
        }
    }

    .form-button {
        border-top: 1px solid #ededed;
        width: 100%;
        display: flex;
        justify-content: center;
        padding: 8px;

        button {
            margin: 0 4px;
            width: 88px;
            height: 32px;
        }
    }
}

/*
.address-information {
    display: flex;
    flex: 1;
    dl {
        display: flex;
        flex-direction: column;
    }
    dt {
        border-bottom: 1px solid #dcdcdc;
        line-height: 42px;
        padding: 0 16px;
        height: 41px;
        box-sizing: border-box;
        color: #000000;
        display: flex;

        strong {
            font-weight: 600;
            font-size: 16px;
        }
        span {
            text-decoration: underline;
            cursor: pointer;
            margin-left: 6px;
            font-size: 14px;
            font-weight: 400;
            text-decoration: underline;
            color: #555;
            &:hover {
                color: #ea4c89;
            }
        }
    }
    dd {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
        padding: 24px 16px;
    }

    .address-detail {
        flex: 1;
        h3 {
            font-size: 36px;
            font-weight: 600;
            color: #000000;
            line-height: 42px;
            margin-bottom: 18px;
            word-break: break-word;
        }
        p {
            font-size: 16px;
            color: #000000;
            line-height: 34px;
        }
    }

    .address-logistics {
        width: 332px;
        white-space: nowrap;
        border-left: 1px solid #dcdcdc;

        // p {
        //     &:first-child {
        //         margin-top: 0;
        //     }
        //     word-break: break-word;
        //     white-space: initial;
        //     min-height: 18px;
        // }
    }


}

*/
</style>
